package com.changhong.autopairservice.core;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.IBinder;

import com.changhong.autopairservice.R;
import com.changhong.autopairservice.utils.Common;

import java.util.Timer;
import java.util.TimerTask;

//by: yazhou.zhu@changhong.com
public class MainService extends Service implements AutoPairManager.AutoPairCallback {
    private static final int NOTIFICATION_ID = 1001;
    private static final String CHANNEL_ID = "AutoPairServiceChannel";
    private AutoPairManager mAutoPairManager;
    private Timer mTimer;
    private TimerTask mTimerTask;
    private BluetoothStateReceiver mBluetoothStateReceiver;

    // Bluetooth state receiver to handle Bluetooth on/off events
    private class BluetoothStateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("android.bluetooth.adapter.action.STATE_CHANGED".equals(action)) {
                int state = intent.getIntExtra("android.bluetooth.adapter.extra.STATE", -1);
                switch (state) {
                    case BluetoothAdapter.STATE_ON:
                        Common.log("Bluetooth turned on, initializing AutoPairManager");
                        init();
                        break;
                    case BluetoothAdapter.STATE_OFF:
                        Common.log("Bluetooth turned off, stopping AutoPairManager");
                        if (mAutoPairManager != null) {
                            mAutoPairManager.stop();
                        }
                        cancelTimer();
                        break;
                }
            }
        }
    }

    private class AutoPairTimerTask extends TimerTask {

        public void run() {
            Common.log("MainService.AutoPairTimerTask.run()");
            if (mAutoPairManager != null) {
                mAutoPairManager.setKeepAlive(false);
            }
            cancelTimer();
            if (mAutoPairManager != null && mAutoPairManager.isAlwaysRunning()) {
                if (mAutoPairManager.isConnected()) {
                    Common.log("A. AutoPairTimerTask.run, isAlwaysRunning = " + mAutoPairManager.isAlwaysRunning() + " , isConnected = " + mAutoPairManager.isConnected());
                    stopSelf();
                }
                Common.log("B. AutoPairTimerTask.run, isAlwaysRunning = " + mAutoPairManager.isAlwaysRunning() + " , isConnected = " + mAutoPairManager.isConnected());
                return;
            }
            Common.log("C. AutoPairTimerTask.run, isAlwaysRunning = " + (mAutoPairManager != null ? mAutoPairManager.isAlwaysRunning() : "null") + " , isConnected = " + (mAutoPairManager != null ? mAutoPairManager.isConnected() : "null"));
            stopSelf();
        }
    }

    public IBinder onBind(Intent intent) {
        Common.log("MainService.onBind()");
        return null;
    }

    public void onCreate() {
        super.onCreate();
        Common.log("MainService.onCreate()");
        
        // Create notification channel for Android 8.0+
        createNotificationChannel();
        
        // Register Bluetooth state receiver
        mBluetoothStateReceiver = new BluetoothStateReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.bluetooth.adapter.action.STATE_CHANGED");
        registerReceiver(mBluetoothStateReceiver, filter);
        
        // Start foreground service
        startForeground(NOTIFICATION_ID, createNotification());
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "Auto Pair Service",
                    NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("Auto Pair Service Channel");
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }

    private Notification createNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return new Notification.Builder(this, CHANNEL_ID)
                    .setContentTitle("Auto Pair Service")
                    .setContentText("Automatic pairing service is running")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .build();
        } else {
            return new Notification.Builder(this)
                    .setContentTitle("Auto Pair Service")
                    .setContentText("Automatic pairing service is running")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .build();
        }
    }

    private void init() {
        // Check if Bluetooth is enabled
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
            Common.log("Bluetooth is not enabled, skipping initialization");
            return;
        }

        if (mAutoPairManager == null) {
            mAutoPairManager = new AutoPairManager(this, this);
        }
        Common.log("This is init!!!");
        if (mAutoPairManager.start()) {
            if (mAutoPairManager != null) {
                mAutoPairManager.setKeepAlive(true);
            }
            cancelTimer();
            if (mAutoPairManager != null) {
                Common.log("MainService.startTimer(),KeepAliveDuration = " + mAutoPairManager.getKeepAliveDuration());
                startTimer();
            }
            return;
        }
        cancelTimer();
        stopSelf();
    }

    private void startTimer() {
        Common.log("MainService.startTimer()");
        mTimer = new Timer();
        mTimerTask = new AutoPairTimerTask();
        if (mAutoPairManager != null) {
            mTimer.schedule(mTimerTask, (long) ((mAutoPairManager.getKeepAliveDuration() * 1000) * 60));
        }
    }

    private void cancelTimer() {
        Common.log("MainService.cancelTimer()");
        if (mTimer != null) {
            mTimer.cancel();
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
        }
        mTimer = null;
        mTimerTask = null;
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        Common.log("MainService.onStartCommand()");
        
        // Initialize the service
        init();
        
        // Return START_STICKY to restart the service if it's killed
        return START_STICKY;
    }

    public void onDestroy() {
        super.onDestroy();
        Common.log("MainService.onDestroy()");
        cancelTimer();
        if (mAutoPairManager != null) {
            mAutoPairManager.stop();
        }
        
        // Unregister Bluetooth state receiver
        if (mBluetoothStateReceiver != null) {
            unregisterReceiver(mBluetoothStateReceiver);
            mBluetoothStateReceiver = null;
        }
        
        // 移除System.exit(0)调用，改为更安全的方式
    }

    public void onStopService() {
        Common.log("MainService.onStopService()");
        cancelTimer();
        stopSelf();
    }
}